/**
 *
 * Copyright 2012 TeleNav, Inc. All rights reserved.
 * MapDataRequest.java
 *
 */
package com.telenav.snowsweeper.net;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

/**
 *@author hhzhu
 *@date 2012-12-7
 */
public abstract class AbstractRequest implements IRequest
{

    private ICallBack caller;
    private boolean isCancelled = false;
    
    public AbstractRequest(ICallBack caller)
    {
        this.caller = caller;
    }

    public  ICallBack getCaller()
    {
        return caller;
    }
    
    public void execute()
    {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet request = new HttpGet(getRequestUrl());
        try
        {
            HttpResponse response = httpClient.execute(request);
            if(!isCancelled && response.getStatusLine().getStatusCode() == 200)
            {
                Header[] header = response.getAllHeaders();
                HashMap<String, String> hm = new HashMap<String, String>();
                for (int i = 0; i < header.length; i++)
                {
                    hm.put(header[i].getName(), header[i].getValue());
                }

                HttpEntity entity = response.getEntity();
                InputStream is = entity.getContent();
                BufferedReader in = new BufferedReader(new InputStreamReader(is));
                String str = "";
                StringBuffer s = new StringBuffer("");
                while ((str = in.readLine()) != null)
                {
                    s.append(str);
                }
                if(!isCancelled)
                {
                    this.caller.parseData(this, s.toString());
                }
            }
            else
            {
                isCancelled = false;
                this.caller.failedRequest(this);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            isCancelled = false;
            this.caller.failedRequest(this);
        }
        finally
        {
            httpClient.getConnectionManager().shutdown();
        }
    }
    
    public void cancel()
    {
        isCancelled = true;
    }
    
    public boolean isCancelled()
    {
        return isCancelled;
    }
}
